package middlewares

import (
	"ecms/config"
	"ecms/models"
	"ecms/utils/hash"
	"ecms/utils/response"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

func AdminAccessToken() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		authorization := ctx.GetHeader("Authorization")
		token := strings.TrimPrefix(authorization, "Bearer ")
		token = strings.TrimSpace(token)
		if authorization == "" || token == "" {
			response.AuthRequired(ctx, "请先登录")
			return
		}
		tokenInfo, err := hash.DecryptAdminAccessToken(token)
		if err != nil {
			response.AuthRequired(ctx, "请先登录")
			return
		}

		nowUnixSeconds := time.Now().Local().Unix()

		// 检查是否过期
		if tokenInfo.ExpiresAt < nowUnixSeconds {
			response.AuthRequired(ctx, "登录会话已过期")
			return
		}

		// 是否已到续期时间
		if tokenInfo.ExpiresAt-nowUnixSeconds <= config.Hash().AdminAccessTokenAutoRefreshAtLeastSeconds {
			newToken, err := hash.EncryptAdminAccessToken(tokenInfo.Model)
			if err != nil {
				response.AuthRequired(ctx, "登录会话异常, 请重新登录")
				return
			}
			ctx.Header("Token-Refresh", newToken)
		}

		ctx.Set("admin_user", &tokenInfo.Model)
	}
}

func GetAdminUser(ctx *gin.Context) (*models.AdminMember, bool) {
	userInfo, has := ctx.Get("admin_user")
	if !has {
		return nil, false
	}
	return userInfo.(*models.AdminMember), true
}
